package com.chendx.store.goods.mq.listenner;

import com.chendx.model.common.dtos.ResponseResult;
import com.chendx.store.common.constants.goods.GoodsConstants;
import com.chendx.store.goods.config.ApplicationContextProvider;
import com.chendx.store.goods.netty.MyWebSocketHandler;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.HashMap;

/**
 * Created by chendx on 2022/4/25.
 */
public class SysNoticeListener implements ChannelAwareMessageListener {

    private static ObjectMapper MAPPER = new ObjectMapper();

    private StringRedisTemplate redisTemplate = ApplicationContextProvider.getApplicationContext().getBean(StringRedisTemplate.class);


    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        String queueName = message.getMessageProperties().getConsumerQueue();
        String username = queueName.substring(queueName.lastIndexOf("_") + 1);

        io.netty.channel.Channel wsChannel = MyWebSocketHandler.userChannelMap.get(username);

        if (wsChannel != null){
            redisTemplate.boundHashOps(GoodsConstants.NO_READ_GOODS_NOTICE).increment(username,1);
            HashMap countMap = new HashMap();
            countMap.put("sysNoticeCount", 1);
            ResponseResult responseResult = ResponseResult.okResult(countMap);
            //把数据通过WebSocket连接主动推送用户
            wsChannel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(responseResult)));
        }
    }
}
